// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require(CONFIG.BasePath + "js/enterprise/base");
	var router = require("../hash/pageRouter");
	var css_apply_upload = require("./apply_upload_material.css");
	var fileElementId;
	var materialFileuuid = []; //证明材料FileUuid
	var templateName = []; //模版名称
	var templateId = []; //模版ID
	var commodityCategoryId = [];
	var evidentiaryCategoryId = [];
	var evidentiaryId = []
	var financeId; //融资信息ID
	var productType;
	var userID;
	var materials = [];
	var str1 = '<div class="fuid" ><a class="financeEvidentiary" fileUuid="" target="_blank"><img class="short" src="../../../res/png/contract1.png" /></a><img style="cursor:pointer;" class="sub1" src="../../../res/png/sub_icon.png" /><span></span></div>';
	var str2 = '<div class="fuid" ><a fileUuid="" target="_blank"><img class="short" src="../../../res/png/contract1.png" /></a><img style="cursor:pointer;" class="sub1" src="../../../res/png/contract2.png" /><span></span></div>';
	var fileUuid;
	var flag = false;
	var tools = require("tools");
	var init = function(page) {
		//禁止通过返回上一页返回本页
		history.go(1);
		financeId = page.params.financeId;
		userID = page.params.userID;
		productType = page.params.productType;
		if (productType == 4) {
			$("#progress").attr("src", "../../../res/png/progress_apply21.png");
		}
		commodityCategoryId = page.params.bulkstockCategoryId;
		
		//若未登录，则返回登陆页面
		if (userID == null && (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined)) {
			location.href = "../login/login.html";
		}

		router.init();
		getCommodityCategoryDetail();
		initEvent();
	};

	var initEvent = function() {

		$("#main").on("change", ".approve input", function() {
			fileElementId = $(this).attr("id");
			uploadMaterial(fileElementId);
		});

		$("#main").on("click", "#backToModifyApply", function() {
			location.href = "../apply/apply_main.html?financeId=" + financeId + "&productType=" + productType;
		});
		
		$("#next_upload_material").unbind("click").click(function(){
			var uploadMust = $(".uploadMust");
			if (uploadMust.length == 0) {
				flag = true;
			}
			for (var j = 0; j < uploadMust.length; j++) {
				if ($(uploadMust[j]).parent().parent().find("a").length <= 0) {
					$(".error_info").css("visibility", "visible");
					flag = false;
					break;
				} else {
					flag = true;
				}
			}
			if (flag) {
				supplementFinanceEvidentiary();
			} else {
				$(".error_info").css("visibility", "visible");
			}
		});

//		$("#main").on("click", "#next_upload_material", function() {
//			var uploadMust = $(".uploadMust");
//			if (uploadMust.length == 0) {
//				flag = true;
//			}
//			for (var j = 0; j < uploadMust.length; j++) {
//				if ($(uploadMust[j]).parent().parent().find("a").length <= 0) {
//					$(".error_info").css("visibility", "visible");
//					flag = false;
//					break;
//				} else {
//					flag = true;
//				}
//			}
//			if (flag) {
//				tools.protectDoubleClick();
//				supplementFinanceEvidentiary();
//			} else {
//				$(".error_info").css("visibility", "visible");
//			}
//		});
	};
	
	//查询融资信息详情
    var inquireFinanceApplicationDetail = function(){
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			async: false,
			nocode: true,
			oData: {
                financeId: financeId
            }, //传递参数
            fnSuccess: function(data) {
                if (data.status == 200) {
                	
                	$.each($(".materiaData"), function() {
                		var $this1 = $(this);
            			$.each(data.datas[0].evidentiaryCategorys, function() {
                			var _this = this;
                			if(_this.evidentiarys.length>0){
                				if(_this.templateId == parseInt($this1.attr("templateId"))){
                					$.each(_this.evidentiarys, function() {
                						var str3 = '<div class="fuid"><a evidentiaryCategoryId="'+_this.evidentiaryCategoryId+'" evidentiaryId="'+this.evidentiaryId+'" templateId="'+_this.templateId+'" templateName="'+_this.templateName+'" materialFileuuid="'+this.materialFileuuid+'" href="/finance/api/v1.0/downloadFile.file?fileUuid='+this.materialFileuuid+'" class="financeEvidentiary" fileUuid="'+this.materialFileuuid+'" target="_blank"><img class="short" src="../../../res/png/contract1.png" /></a><img style="cursor:pointer;" class="sub1" src="../../../res/png/sub_icon.png" /><span>'+ tools.inquireFile(this.materialFileuuid) +'</span></div>';
	                					$this1.find("input[type=file]").before(str3);
                					});
	                			}else{}
                			}
                		});
                	});
                	
                	$(".sub1").unbind("click").click(function(){
                		$(this).parent().remove();
                	});
                	
                } else {
//                  base.alert(2,"信息获取失败");
                }
            }
		});
	};

	//获取大宗商品类别详情
	var getCommodityCategoryDetail = function() {
		base.fnAjax({
			action: "inquireBulkstockCategoryDetail.json",
			async: false,
			nocode: true,
			oData: {
				bulkstockCategoryId: commodityCategoryId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#approveTpl").html();
					var html = juicer(tpl, data);
					$("#approveBody").html(html);
					
					inquireFinanceApplicationDetail();
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//增补融资申请证明材料
	var supplementFinanceEvidentiary = function() {
		if ($(".financeEvidentiary").length > 0) {
			$.each($(".financeEvidentiary"), function(i, val) {
				materialFileuuid.push($(this).attr("materialFileuuid"));
				templateName.push($(this).attr("templateName"));
				templateId.push($(this).attr("templateId"));
				evidentiaryCategoryId.push($(this).attr("evidentiaryCategoryId"));
				evidentiaryId.push($(this).attr("evidentiaryId"));

			});

			base.fnAjax({
				action: "supplementFinanceEvidentiary.json",
				async: false,
				nocode: true,
				oData: {
					materialFileuuid: materialFileuuid,
					evidentiaryId: evidentiaryId,
					templateName: templateName,
					templateId: templateId,
					evidentiaryCategoryId: evidentiaryCategoryId,
					financeId: financeId
				}, //传递参数
				fnSuccess: function(data) {
					tools.cancelProtectDoubleClick();
					if (data.status == 200) {
						router.route("apply/apply_success.html?financeId=" + financeId + "&userID=" + userID + "&productType=" + productType);
					} else {
						base.alert(2, data.message);
					}
				}
			});
		}else{
			router.route("apply/apply_success.html");
		}
	};

	//上传文件
	var uploadMaterial = function(fileElementId) {
		$.ajaxFileUpload({
			url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
			secureuri: false,
			fileElementId: fileElementId,
			dataType: 'json',
			async: true,
			success: function(data) {
				var dom = $(document.getElementById(fileElementId));
				dom.before(str1);
				dom.parent().find("a:last").attr({
					"href": "/finance/api/v1.0/downloadFile.file?fileUuid=" + data.data[0].fileUuid,
					"materialFileuuid": data.data[0].fileUuid,
					"templateName": dom.parents(".materiaData").attr("templateName"),
					"templateId": dom.parents(".materiaData").attr("templateId"),
					"evidentiaryCategoryId": 0,
					"evidentiaryId": 0
				});
				dom.parent().find("span:last").html(data.data[0].fileName);
				dom.parent().find(".sub1:last").click(function() {
					$(this).parent().remove();
				});
			},
			complete: function(xml) {},
			error: function(data, status, e) {
				if (data.msg == null) {
					base.alert(2, "文件太大无法上传");
				} else {
					base.alert(2, data.msg);
				}
			}
		});
	};

	return {
		init: init
	};
});